
#///// Nouvelle Version //////
library(tm);
library(proxy);
source("supp_balises.R");
source("charge_corpus.R");

charge.un.document <- function(name){
  doc <- readLines(name);
  texte <- PlainTextDocument(doc);
  texte <- extract_text(texte);  
  texte <- removeWords(texte, stopwords("english"));
  texte <- removePunctuation(texte);
  write(texte, file="./fichier/doc.txt");
  return(texte);
}

charge.corpus.classe <- function(dossier, name){
  corpus = Corpus(DirSource(paste(paste(dossier, name, sep=""), "/", sep="")), readerControl=list(reader=readPDF));
  corpus <- tm_map(corpus, extract_text);
  corpus <- tm_map(corpus, removeWords, stopwords("english"));
  corpus <- tm_map(corpus, removePunctuation);

  return(corpus);
}

enregistre.all.corpus <- function(dossier="../../ProjetPDF/"){
  rep <- dir(dossier);

  for(i in 1:length(rep)){
    corpus <- charge.corpus.classe(dossier, rep[i]);
    for(j in 1:length(corpus))
      writeChar(corpus[[j]], paste("donnees/", rep[i], "/", rep[i], "_", j, ".txt", sep=""));

    print(paste("Terminé pour ", rep[i], "...", i*100/length(rep), sep=""));
  }
  print("Terminé 100%");
}

recuperer.corpus <- function(name){
  return(Corpus(DirSource(paste("donnees/", name, "/", sep=""))));
}

recuperer.texte <- function(){
  return(Corpus(DirSource("./fichier/")));
}

modif <- function(n, corpus, texte){
  return(dissimilarity(corpus[[n]], texte, method="cosine"));
}

classer <- function(name){
  rep <- dir("donnees/");
  mini <- 1;
  charge.un.document(name);
  texte <- recuperer.texte();
  for(i in 1:length(rep)){
    corpus <- recuperer.corpus(rep[i]);
    m <- DocumentTermMatrix(corpus);
    val <- mean(sapply(1:length(corpus), modif, corpus, texte[[1]]));
    mini <- min(val, mini);
    if(mini == val) classe = i;
    print(paste(rep[i], " : ", val, sep=""));
  }
  return(paste("Classer dans ", rep[classe], sep=""));  
}
